package com.ice.body.business.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.ice.base.model.SysLoginModel;
import com.ice.base.result.AjaxResult;
import com.ice.base.util.BaseUtil;
import com.ice.body.business.dao.ReagentStockDao;
import com.ice.body.business.model.*;
import com.ice.body.business.service.*;
import com.ice.base.dao.BaseDao;
import com.ice.base.service.impl.BaseServiceImpl;
import com.ice.body.business.vo.ReagentStockVo;
import com.ice.body.dashboard.model.TotalStockVo;
import com.ice.body.log.model.LogDestroy;
import com.ice.body.log.service.LogDestroyService;
import com.ice.body.rpc.dto.ReagentStockDto;
import com.ice.postek.PrintRfidLableUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * Created with GuoYanBin.
 * Description:业务接口-试剂库存 serviceImpl
 * Date: 2021-06-22
 * Time: 10:15
 */
@Service
public class ReagentStockServiceImpl extends BaseServiceImpl<ReagentStock> implements ReagentStockService{
    @Resource 
    private ReagentStockDao reagentStockMapper;
    @Resource
    private LogDestroyService logDestroyService;
    @Resource
    private RecordLabService reagentRecordService;
    @Resource
    private ReagentMsdsService reagentMsdsService;
    @Resource
    private ReagentAreaService reagentAreaService;
    @Resource
    private CabinetService cabinetService;
    @Resource
    private RecordCabinetService recordCabinetService;
    @Resource
    private ReagentStockService reagentStockService;
    @Resource
    private ReagentOwnService reagentOwnService;
    @Resource
    private RecordLabService recordLabService;


    @Override
    public BaseDao<ReagentStock> getBaseDao() {
        return reagentStockMapper;
    }

    /**
     * 批次庚新浓度
     * @param model
     * @return
     */
    @Override
    public AjaxResult batchUpdateImpurity(ReagentStock model) {


        Integer integer = reagentStockMapper.batchUpdateImpurity(model);
        System.out.println("批量修改 ：" + integer    );
        return AjaxResult.success();
    }

    /**
     * 实验室+柜子 柜子上传数据只做记录
     * @param model
     * @return
     */
    @Override
    public AjaxResult cabinetRecord(ReagentStockDto model) {
        String serialNo = model.getSerialNo();
        String cabNo = model.getCabNo();
        String opeType  = model.getOpeType();
        try{
            Cabinet cabinetModel = cabinetService.getBySerialNo(serialNo);
            if(StringUtils.isEmpty(opeType) || null == cabinetModel){
                return AjaxResult.error("上传数据错误,序列号不存在或操作类型未空,请检查后提交");
            }
            RecordCabinet recordCabinet;
            List<ReagentStock> list = model.getList();
            for (ReagentStock r:list) {
                ReagentStock stock = reagentStockService.getByEpcCode(r.getEpcCode());
                if(null == stock){
                    continue;
                }
                recordCabinet = new RecordCabinet();
                BeanUtil.copyProperties(stock,recordCabinet,false);
                recordCabinet.setOpeType(opeType);
                recordCabinet.setCreateTime(new Date());
                recordCabinetService.insert(recordCabinet);
                //试剂1入库/2出库/3归还/0销毁
                if("1".equals(opeType) ||"3".equals(opeType) ){
                    //入库或者归还需要修改cabNo号
                    stock.setCabNo(Long.parseLong(model.getCabNo()) );
                    this.reagentStockService.update(stock);
                }

            }

/*
            if("1".equals(opeType)){//入库
                this.inStock(model,cabinetModel);
            }else if("2".equals(opeType)){//出库
                this.outStock(model,cabinetModel);
            }else if("3".equals(opeType)){//归还
                this.backStock(model,cabinetModel);
            }else if("0".equals(opeType)){//销毁
                this.destroyStock(model,cabinetModel);
            }*/
        }catch (Exception e ){
            e.printStackTrace();
            AjaxResult.error("操作错误");
        }
        return AjaxResult.success("操作成功");
    }

    @Override
    @Transactional
    public void printRFID(ReagentStock stock) throws Exception {
        String comEpcNo  = "";
        List<Map> mapList ;
        ReagentMsdsModel msds = reagentMsdsService.getByCasNo(stock.getCasNo());
        String areaId = stock.getAreaId();
        ReagentAreaModel reagentAreaModel = reagentAreaService.selectById(areaId);
        if(null != reagentAreaModel){
            stock.setAreaName(reagentAreaModel.getAreaName());
        }


        ReagentOwn ownModel = reagentOwnService.getByCname(stock.getCName());
        if(null != ownModel && null != ownModel.getTotalCount() ){
            ownModel.setTotalCount(ownModel.getTotalCount() + stock.getPrintCount());
            reagentOwnService.update(ownModel);
        }
        //----------组织数据------------------
        if(null == msds){
            comEpcNo = BaseUtil.getRandom(6);
        }else{
            comEpcNo = msds.getComEpcNum();
        }
        stock.setLeftWeigh(stock.getLeftWeigh());
        stock.setCreateTime(new Date());
        stock.setState("1");//1在库
        Map epcMap = null;

        for (int i = 0; i < stock.getPrintCount(); i++) {
            //停止1秒 防止ecp码重复
            TimeUnit.SECONDS.sleep(1);
            String epcCode = comEpcNo + DateUtil.format(new Date(), "yyyyMMddHHmmssSSS") + BaseUtil.getRandom(1);
            stock.setEpcCode(epcCode);
            if (reagentStockMapper.insert(stock)>0) {
                //  reagentEpcList.add(reagentEpc);
                mapList = new ArrayList<>();
                epcMap = new HashMap();
                epcMap.put("name", stock.getCName());
                epcMap.put("fineness", stock.getFineness());
                epcMap.put("casNo", stock.getCasNo());
                epcMap.put("site", stock.getAreaName());
                epcMap.put("batchNo", stock.getBatchNo());
                epcMap.put("epc", stock.getEpcCode());
                mapList.add(epcMap);
                PrintRfidLableUtil.printRfidLable(mapList);
            }
        }


    }


    @Override
    public void printEpc(String epcCode) throws Exception {
        if (StringUtils.isNotEmpty(epcCode)) {
            ReagentStock stock = this.getByEpcCode(epcCode);
            if (null != stock) {
                List<Map> mapList = new ArrayList<>();
                HashMap epcMap = new HashMap();
                epcMap.put("epc", stock.getEpcCode());
                epcMap.put("date", "有效期至:" +  stock.getExpireTimeEnd());
                epcMap.put("name", stock.getCName());
                mapList.add(epcMap);
                PrintRfidLableUtil.printRfidLable(mapList);// 打印RFID标签
            }
        }
    }


    /**
     * 查询汇总
     * @return
     */
    @Override
    public ArrayList<ReagentStockVo> selectTotal() {
        return reagentStockMapper.selectTotal();
    }

    @Override
    public ReagentStock getByEpcCode(String epcCode) {
        return reagentStockMapper.getByEpcCode(epcCode);
    }

    @Override
    public String getStateByEpcCode(String epcCode) {
        return reagentStockMapper.getStateByEpcCode(epcCode);
    }

    @Override
    public Integer checkReagentInWarehouse(ReagentStock model) {
        return reagentStockMapper.checkReagentInWarehouse(model);
    }

    @Override
    public void insertModel(ReagentStock model) {
        reagentStockMapper.insertModel(model);
    }

    @Override
    public Integer batchUpdate(SysLoginModel user, List<String> epcList,String state) {
        for(int i = 0;i < epcList.size();i++){
            ReagentStock stock = new ReagentStock();
            stock.setEpcCode(epcList.get(i));
            stock.setState(state);// 1 在库  2外借  state=3是归还 状态也要改为子啊库
            if("3".equals(state)){
                stock.setState("1");
            }

            reagentStockMapper.updateByEpcCode(stock) ;

            ReagentStock epcModel = reagentStockService.getByEpcCode(epcList.get(i));
            //记录
            RecordLab prModel = new RecordLab();
            prModel.setCreateTime(new Date());
            prModel.setState(Integer.parseInt(state)); //1入库 2出库 3归还
            prModel.setCName(epcModel.getCName());
          //  prModel.setCasNo(epcModel.getCasNo());
          //  prModel.setUserId(user.getId());
            prModel.setUserName(user.getRealName());
            prModel.setEpcCode(epcModel.getEpcCode());

            reagentRecordService.insert(prModel);



        }
        return 1;
    }

    /**
     * 试剂销毁
     * @param model
     * @return
     */
    @Override
    @Transactional
    public Integer destroy(LogDestroy model) {
        String epcCode = model.getEpcCode();
        try{

            //将库存表状态改为 9 无效
            ReagentStock stockModel = this.getByEpcCode(epcCode);
            if(null == stockModel){
                return 0;
            }
            stockModel.setState("8");
            reagentStockMapper.update(stockModel);
            //增加试剂流向记录
            RecordLab record = new RecordLab();
            BeanUtils.copyProperties(stockModel,record);
            SysLoginModel currLoginModel = BaseUtil.getCurrLoginModel();
            record.setUserName(currLoginModel.getRealName());
            record.setState(8);
            record.setId(null);
            record.setCreateTime(new Date());
            reagentRecordService.insert(record);

            //增加销毁记录
            model.setUserName(currLoginModel.getRealName());
            model.setCName(stockModel.getCName());
            model.setCreateTime(new Date());
            return logDestroyService.insert(model);

        }catch (Exception e ){
            e.printStackTrace();
            System.out.println("销毁失败："+ e.getMessage());
        }
        return 1;

    }

    /**
     * 手动入库
     * @param stock
     * @return
     */
    @Override
    @Transactional
    public boolean enterWarehouse(ReagentStock stock) {
        String epcCode = stock.getEpcCode();
        boolean flagVal = false;
        long rsId ;
        ReagentStock stocks = reagentStockService.getByEpcCode(epcCode);// 根据epc编号查询药品信息
        SysLoginModel user = BaseUtil.getCurrLoginModel();
        if(null != stocks && null != user){
            stocks.setState("1");//1代表在库
            reagentStockMapper.update(stocks);

        }
        RecordLab prModel = new RecordLab();
        prModel.setCreateTime(new Date());
        prModel.setState(1); //1入库
        prModel.setCName(stocks.getCName());
        prModel.setUserName(user.getRealName());
        prModel.setEpcCode(epcCode);
        if(reagentRecordService.insert(prModel) > 0){
            flagVal = true;
        }
        return flagVal;
    }

    @Override
    @Transactional
    public boolean outWarehouse(ReagentStock model) {
        boolean flagVal = false;
        SysLoginModel user = BaseUtil.getCurrLoginModel();
        model.setState("2");
        reagentStockMapper.update(model);
        RecordLab prModel = new RecordLab();
        prModel.setCreateTime(new Date());
        prModel.setState(2); //2入库
        prModel.setCName(model.getCName());
     //   prModel.setCasNo(model.getCasNo());
    //    prModel.setUserId(user.getId());
        prModel.setUserName(user.getRealName());
        prModel.setEpcCode(model.getEpcCode());
        if(reagentRecordService.insert(prModel) > 0){
            flagVal = true;
        }
        return  flagVal;
    }

    /**
     * 批量结算入库
     * @param list
     * @param warehouseId
     * @return
     */
    @Override
    @Transactional
    public boolean batchInStock(SysLoginModel user, List<ReagentStock> list, String warehouseId) {
        Boolean returnFlag = true;
       // WareHouseModel wareHouseModel = wareHouseService.selectById(warehouseId);
        try{
            for (ReagentStock model :list ) {
                if(null == model){
                    continue;
                }
                //1修改状态
                model.setState("1");//1 已入库
                model.setInStockTime(new Date());
                reagentStockService.update(model);
                //记录
                RecordLab prModel = new RecordLab();
                prModel.setCreateTime(new Date());
                prModel.setState(1); //1入库
                prModel.setEpcCode(model.getEpcCode());
                prModel.setCName(model.getCName());
                prModel.setUserName(user.getRealName());
                reagentRecordService.insert(prModel);
            }
        }catch (Exception e){
            returnFlag = false;
            e.printStackTrace();
        }
        return returnFlag;
    }

    /**
     * 结算出库
     * @param stockList
     * @param verifyUser
     * @return
     */
    @Override
    public Integer batchOutStock(List<ReagentStock> stockList, String verifyUser) {
        for (ReagentStock model :stockList ) {
            if(null == model || StringUtils.isEmpty(model.getEpcCode())){
                continue;
            }
            // 2是在库状态
            if("1".equals(model.getState())){
                model.setState("2");
            }
            RecordLab prModel = new RecordLab();
            //私有库统计-1
            ReagentOwn byCname = reagentOwnService.getByCname(model.getCName());
            if(null != byCname){
                byCname.setTotalCount(byCname.getTotalCount()-1);
                reagentOwnService.update(byCname);
                prModel.setCasNo(byCname.getCasNo());
            }

            reagentStockMapper.updateByEpcCode(model) ;
            //记录

            prModel.setCreateTime(new Date());
            prModel.setState(2); //1入库 2出库 3归还
            prModel.setCName(model.getCName());
            prModel.setCasNo(model.getCasNo());

            //  prModel.setUserId(user.getId());
            prModel.setUserName(verifyUser);
            prModel.setEpcCode(model.getEpcCode());
            recordLabService.insert(prModel);
        }
        return 1;
    }


 /**
     * 结算归还
     * @param stockList
     * @param verifyUser
     * @return
     */
    @Override
    public Integer batchBackStock(List<ReagentStock> stockList, String verifyUser) {
        for (ReagentStock model :stockList ) {
            if(null == model || StringUtils.isEmpty(model.getEpcCode())){
                continue;
            }
            // 1是在库状态
            if("2".equals(model.getState())){
                model.setState("1");
            }
            RecordLab prModel = new RecordLab();
            //私有库统计+1
            ReagentOwn byCname = reagentOwnService.getByCname(model.getCName());
            if(null != byCname){
                byCname.setTotalCount(byCname.getTotalCount()+1);
                reagentOwnService.update(byCname);
                prModel.setCasNo(byCname.getCasNo());
            }

            reagentStockMapper.updateByEpcCode(model) ;
            //记录

            prModel.setCreateTime(new Date());
            prModel.setState(3); //1入库 2出库 3归还
            prModel.setCName(model.getCName());
            prModel.setCasNo(model.getCasNo());

            //  prModel.setUserId(user.getId());
            prModel.setUserName(verifyUser);
            prModel.setEpcCode(model.getEpcCode());
            recordLabService.insert(prModel);
        }
        return 1;
    }
























    /**
     * 获取过期试剂
     * @return
     */
    @Override
    public void getExpireReagent() {
        List<ReagentStock> list = reagentStockMapper.getExpireReagent();
        if(CollectionUtil.isNotEmpty(list)) list.forEach(a -> {
            //转存到过期预警表
            ReagentStock expireModel = new ReagentStock();
            BeanUtils.copyProperties(a, expireModel);
            expireModel.setId(null);
            if (reagentStockMapper.insertToExpire(expireModel) > 0) {
                //修改过期试剂状态
                a.setState("9");
                reagentStockMapper.update(a);
            }
        });
    }

    @Override
    public List<ReagentStock> getExpireWarning() {
        return reagentStockMapper.getExpireWarning();
    }

    @Override
    public void deleteExpire(Integer id) {

        reagentStockMapper.deleteExpire(id);
    }

    /**
     * 数据看板  获取库存剩余数据
     * @return
     */
    @Override
    public ArrayList<TotalStockVo> getTotalStock() {
        return reagentStockMapper.getTotalStockLimit();
    }


}
